'use strict'

module.exports = init;

var cacheStore = require('./cacheStore')()
var defaultSetting = {
    expireTime: 9999
}
var setting;

function init(opt){
    //Default settings
    setting = Object.assign({},defaultSetting,opt)

    return (req,res,next) => {
        var sid = req.headers['my-cookie']

        if(!sid){
            console.warn('Header "my-cookie" not define.')
            next()
            return
        }


        req.session = cacheStore.getOrNewObjByKey(sid,setting.expireTime)
        req.session.expireCallback = session => {
            console.log('Expired: '+session.id)

            //Exit room
            if(session.room){
                console.log('Exit room: '+session.room.roomNum)
                session.room.exit(session.id)
            }

            //logout
            delete session.user
        }
        next()
    }
}

